package cn.bone.zk.zk04;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class CuratorLockTest {

    public static void main(String[] args) {

        // 创建分布式锁1
        InterProcessMutex lock1 = new InterProcessMutex(getCuratorFramework(), "/locks");
        String name1 = "lock1";
        // 创建分布式锁2
        InterProcessMutex lock2 = new InterProcessMutex(getCuratorFramework(), "/locks");
        String name2 = "lock2";
        new Thread(new CuratorLockThread(lock1, name1)).start();
        new Thread(new CuratorLockThread(lock2, name2)).start();

    }

    private static CuratorFramework getCuratorFramework() {

        // 连接失败，3s后重试，一共重试3次
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 3);
        String connectString = "192.168.1.5:2001,192.168.1.5:2002,192.168.1.5:2003";
        int sessionTimeout = 2000;

        // 创建
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(connectString)
                .sessionTimeoutMs(sessionTimeout)
                .connectionTimeoutMs(2000)
                .retryPolicy(retryPolicy)
                .build();

        // 启动客户端
        curatorFramework.start();
        System.out.println("zk start success...");

        return curatorFramework;
    }
}
